﻿using System;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;

namespace SectorPoint.Products.AdRotator
{
	[AspNetHostingPermissionAttribute( SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal )]
	[AspNetHostingPermissionAttribute( SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal )]
	public class AdRotatorEditorPart : System.Web.UI.WebControls.WebParts.EditorPart
	{
		public AdRotatorEditorPart()
		{
			this.ID = "AdRotatorEditorPart";
			this.Title = "Ad Rotator";

			this.PreRender += new EventHandler( AdRotatorEditorPart_PreRender );
		}

		#region Form Controls
		protected Label lblListUrl;
        protected Label lblCustomCssClass;
		protected Label lblJavaScript;
		protected Label lblRotationSpeed;
        protected Label lblTransitionEffect;
        protected TextBox txtListUrl;
		protected HtmlInputButton btnListUrl;
        protected TextBox txtCustomCssClass;
		protected RadioButtonList rblRotation;
		protected DropDownList ddlJavaScript;
		protected TextBox txtRotationSpeed;
		protected DropDownList ddlTransitionEffect;
		protected CheckBox cbPauseOnHover;
		#endregion

		#region Event Handlers

		protected override void CreateChildControls()
		{
			base.CreateChildControls();

			lblListUrl = new Label();
			lblListUrl.Text = "List URL:";
			txtListUrl = new TextBox();
			txtListUrl.ID = "txtListUrl";
			btnListUrl = new HtmlInputButton();
			btnListUrl.Value = "Select List";
			btnListUrl.Attributes.Add( "onclick", "mso_launchListSmtPicker();" );

            lblCustomCssClass = new Label();
            lblCustomCssClass.Text = "CSS Class";
            txtCustomCssClass = new TextBox();
            txtCustomCssClass.ID = "txtCustomCssClass";

			rblRotation = new RadioButtonList();
			rblRotation.ID = "rblRotation";
			rblRotation.Items.Add( new ListItem( "Show a random image every time the page is viewed.", "0" ) );
			rblRotation.Items.Add( new ListItem( "Cycle through all images while the user is viewing the page.", "1" ) );

            #region JavaScript Source
            ddlJavaScript = new DropDownList();
			ddlJavaScript.ID = "ddlJavaScript";
			ddlJavaScript.Items.Add( new ListItem( "Internal", ContentDeliveryOption.Internal.ToString() ) );
			ddlJavaScript.Items.Add( new ListItem( "None", ContentDeliveryOption.None.ToString() ) );
			ddlJavaScript.Items.Add( new ListItem( "Edgecast", ContentDeliveryOption.Edgecast.ToString() ) );
			ddlJavaScript.Items.Add( new ListItem( "Google AJAX CDN", ContentDeliveryOption.Google.ToString() ) );
			ddlJavaScript.Items.Add( new ListItem( "Microsoft AJAX CDN", ContentDeliveryOption.Microsoft.ToString() ) );
			lblJavaScript = new Label();
			lblJavaScript.CssClass = "UserSectionHead";
			lblJavaScript.Text = "jQuery Library Delivery Method:";
            #endregion

			#region RotationSpeed
			lblRotationSpeed = new Label();
			lblRotationSpeed.CssClass = "UserSectionHead";
			lblRotationSpeed.Text = "Rotation Speed (ms):";
			txtRotationSpeed = new TextBox();
			txtRotationSpeed.ID = "txtRotationSpeed";
			#endregion

			#region TransitionEffect
			ddlTransitionEffect = new DropDownList();
			ddlTransitionEffect.ID = "ddlTransitionEffect";
			lblTransitionEffect = new Label();
			lblTransitionEffect.Text = "Transition Effect:";

			ddlTransitionEffect.Items.Add( new ListItem( "Blind X", "blindX" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Blind Y", "blindY" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Blind Z", "blindZ" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Cover", "cover" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Curtain X", "curtainX" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Curtain Y", "curtainY" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Fade", "fade" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Fade Zoom", "fadeZoom" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Grow X", "growX" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Grow Y", "growY" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "None", "none" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Up", "scrollUp" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Down", "scrollDown" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Left", "scrollLeft" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Right", "scrollRight" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Horizontal", "scrollHorz" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Scroll Vertical", "scrollVert" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Shuffle", "shuffle" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Slide X", "slideX" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Slide Y", "slideY" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Toss", "toss" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Turn Up", "turnUp" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Turn Down", "turnDown" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Turn Left", "turnLeft" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Turn Right", "turnRight" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Uncover", "uncover" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Wipe", "wipe" ) );
			ddlTransitionEffect.Items.Add( new ListItem( "Zoom", "zoom" ) );

			this.Controls.Add( lblTransitionEffect );
			this.Controls.Add( ddlTransitionEffect );
			#endregion

			#region PauseOnHover
			cbPauseOnHover = new CheckBox();
			cbPauseOnHover.Text = "Pause image rotation on hover";
			#endregion


			this.Controls.Add( lblListUrl );
            this.Controls.Add( lblCustomCssClass );
			this.Controls.Add( lblJavaScript );
			this.Controls.Add( lblRotationSpeed );
			this.Controls.Add( txtListUrl );
            this.Controls.Add( txtCustomCssClass );
			this.Controls.Add( rblRotation );
			this.Controls.Add( ddlJavaScript );
			this.Controls.Add( txtRotationSpeed );
			this.Controls.Add( cbPauseOnHover );
			lblListUrl.AssociatedControlID = txtListUrl.ID;
            lblCustomCssClass.AssociatedControlID = txtCustomCssClass.ID;
			lblJavaScript.AssociatedControlID = ddlJavaScript.ID;
			lblRotationSpeed.AssociatedControlID = txtRotationSpeed.ID;
			lblTransitionEffect.AssociatedControlID = ddlTransitionEffect.ID;

			this.ChildControlsCreated = true;
		}

		[System.Security.Permissions.FileIOPermission( SecurityAction.LinkDemand )]
		void AdRotatorEditorPart_PreRender(object sender, EventArgs e)
		{
			ScriptLink.Register( this.Page, "PickerTreeDialog.js", true );
			string script = "\r\n                var lastSelectedListSmtPickerId = '';\r\n                function mso_launchListSmtPicker()\r\n                {\r\n                    if (!document.getElementById) return;\r\n\r\n                    var listTextBox = document.getElementById('" + SPHttpUtility.EcmaScriptStringLiteralEncode( this.txtListUrl.ClientID ) + "');\r\n                    if (listTextBox == null) return;\r\n\r\n                    var serverUrl = '" + SPHttpUtility.EcmaScriptStringLiteralEncode( SPContext.Current.Web.ServerRelativeUrl ) + "';\r\n\r\n                    var callback = function(results)\r\n                    {\r\n                        if (results == null \r\n                        || results[1] == null\r\n                        || results[2] == null) return;\r\n\r\n                        lastSelectedListSmtPickerId = results[0];\r\n                        var listUrl = '';\r\n                        if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';\r\n                        if (results[1].charAt(0) == '/') results[1] = results[1].substring(1);\r\n                        listUrl = listUrl + results[1];\r\n                        if (listUrl.substring(listUrl.length-1) != '/') listUrl = listUrl + '/';\r\n                        if (results[2].charAt(0) == '/') results[2] = results[2].substring(1);\r\n                        listUrl = listUrl + results[2];\r\n                        listTextBox.value = listUrl;\r\n                    };\r\n                    LaunchPickerTreeDialog('CbqPickerSelectListTitle','CbqPickerSelectListText','websLists','', serverUrl, lastSelectedListSmtPickerId,'','','/_layouts/images/smt_icon.gif','', callback);\r\n                    \r\n                }";
			this.Page.ClientScript.RegisterClientScriptBlock( typeof( AdRotatorEditorPart ), "mso_launchListSmtPicker", script, true );
		}

		protected override void Render(HtmlTextWriter writer)
		{
			const string m_userDottedLine = @"<div class='UserDottedLine' style='width: 100%; margin: 8px 0 4px 0;'>&nbsp;</div>";

			writer.WriteBeginTag( "div" );
			writer.WriteAttribute( "class", "UserSectionHead" );
			writer.Write( HtmlTextWriter.TagRightChar );
			lblListUrl.RenderControl( writer );
			writer.WriteEndTag( "div" );
			txtListUrl.RenderControl( writer );
			writer.Write( "<br />" );
			btnListUrl.RenderControl( writer );

            writer.Write( m_userDottedLine );
			writer.WriteBeginTag( "div" );
			writer.WriteAttribute( "class", "UserSectionHead" );
			writer.Write( HtmlTextWriter.TagRightChar );
			lblCustomCssClass.RenderControl( writer );
			writer.WriteEndTag( "div" );

			txtCustomCssClass.RenderControl( writer );
			writer.Write( m_userDottedLine );
			writer.Write( "<div class='UserSectionHead'>Rotation Method:</div>" );
			rblRotation.RenderControl( writer );
			writer.Write( m_userDottedLine );
			lblJavaScript.RenderControl( writer );
			ddlJavaScript.RenderControl( writer );
			writer.Write( m_userDottedLine );
			
			writer.WriteBeginTag( "div" );
			writer.WriteAttribute( "class", "UserSectionHead" );
			writer.Write( HtmlTextWriter.TagRightChar );
			lblTransitionEffect.RenderControl( writer );
			writer.WriteEndTag( "div" );

			ddlTransitionEffect.RenderControl( writer );
			writer.Write( m_userDottedLine );
			lblRotationSpeed.RenderControl( writer );
			txtRotationSpeed.RenderControl( writer );
			writer.Write( m_userDottedLine );
			cbPauseOnHover.RenderControl( writer );
		}

		public override bool ApplyChanges()
		{
			EnsureChildControls();
			AdRotatorWebPart parentPart = (AdRotatorWebPart)this.WebPartToEdit;
			parentPart.ListUrl = txtListUrl.Text;
            parentPart.CustomCssClass = txtCustomCssClass.Text;

			switch (rblRotation.SelectedIndex)
			{
				case 0:
					parentPart.Rotation = RotationOption.Once;
					break;
				case 1:
					parentPart.Rotation = RotationOption.Multiple;
					break;
			}

			parentPart.JavaScriptDeliveryMethod = (ContentDeliveryOption)Enum.Parse( typeof( ContentDeliveryOption ), ddlJavaScript.SelectedValue );

			int rotationSpeed;
			if (int.TryParse( txtRotationSpeed.Text, out rotationSpeed ))
				parentPart.RotationSpeed = rotationSpeed;

			parentPart.TransitionEffect = ddlTransitionEffect.SelectedValue;
			parentPart.PauseOnHover = cbPauseOnHover.Checked;


			return true;
		}

		public override void SyncChanges()
		{
			EnsureChildControls();
			AdRotatorWebPart parentPart = (AdRotatorWebPart)this.WebPartToEdit;
			txtListUrl.Text = parentPart.ListUrl;
            txtCustomCssClass.Text = parentPart.CustomCssClass;

			switch (parentPart.Rotation)
			{
				case RotationOption.Once:
					rblRotation.SelectedIndex = 0;
					break;

				case RotationOption.Multiple:
					rblRotation.SelectedIndex = 1;
					break;
			}

			int javaScriptIndex = 0;

			foreach (ListItem javaScriptOption in ddlJavaScript.Items)
			{
				if ((ContentDeliveryOption)Enum.Parse(typeof(ContentDeliveryOption), javaScriptOption.Value) == parentPart.JavaScriptDeliveryMethod)
				{
					javaScriptIndex = ddlJavaScript.Items.IndexOf( javaScriptOption );
				}
			}

			ddlJavaScript.SelectedIndex = javaScriptIndex;
			txtRotationSpeed.Text = parentPart.RotationSpeed.ToString( System.Globalization.CultureInfo.CurrentCulture );
			string transitionEffect = parentPart.TransitionEffect;
			int transitionIndex = 0;
			foreach (ListItem transtitionOption in ddlTransitionEffect.Items)
			{
				if (transtitionOption.Value == transitionEffect)
				{
					transitionIndex = ddlTransitionEffect.Items.IndexOf( transtitionOption );
				}
			}
			ddlTransitionEffect.SelectedIndex = transitionIndex;
			cbPauseOnHover.Checked = parentPart.PauseOnHover;
		}

		#endregion
	}
}
